import store from '../store/index.js'
// import http from './api.js'
//创建全局播放器
let durations; //当前播放的位置 时间
let nowID; //当前播放的音乐id
const play = uni.createInnerAudioContext();


// import moment from '../dependences/moment.js'
///数组去重
function distinct1(arr, key) {
	if (arr == []) return []
	var newobj = {},
		newArr = [];
	for (var i = 0; i < arr.length; i++) {
		var item = arr[i];
		if (!newobj[item[key]]) {
			newobj[item[key]] = newArr.push(item);
		}
	}
	return newArr;
};

// 播放  

function playMusic(url) {
	console.log(url)
	
	// store.commit('getfalg', true)
	play.autoplay = true;
	play.src = url;
	play.onPlay((data) => {
		console.log('开始播放');
	});
	play.onError((res) => {
		// console.log(res.errMsg);
		// console.log(res.errCode);
	});
	//获取播放时长
	play.onCanplay(() => {
		store.state.dt = formatTime(play.duration)
	})
	lookMusicStatus()
	play.onEnded((res) => {
		console.log('结束了')
		// 下一首
		store.commit('setnextPlay', 1)
	})
}
//检测音乐状态
function lookMusicStatus() {
	play.onTimeUpdate((res) => {
		const percentAudio = formatTime(parseInt(play.currentTime));
		const bofang = play.currentTime
		const duration = parseInt(play.currentTime / play.duration * 100) //进度条位置
		//进度条位置 = 当前时常  / 总时常 * 100 
		const longtime = play.duration //总时长
		const data = [percentAudio, duration, bofang, longtime]
		store.commit('getsize', data, )
		// 当前播放 时间  秒形式传入
		store.commit('getcurrent', parseInt(play.currentTime))
		let durations = duration;
	});
}
//暂停
function pause() {
	play.pause()
	store.commit('getfalg', false)
}
//停止
function stop() {
	play.stop();
}
//继续播放
function aiginPlay() {
	play.seek(durations)
	play.play()
	store.commit('getfalg', true)
	lookMusicStatus()
}
// 滑到某个地方播放
function sliderPlay(playTime) {
	play.seek(playTime)
	play.play()
}

//获取 url 并且 播放音乐
function SendMusic(item, index) {
	console.log(item,index);
	// 加入播放列表
	//获取音乐url
	this.$store.dispatch("playIndex", index);
	this.$store.dispatch("playMusic", {
		list: item,
		index: index,
		listid: item.id
	})


	// //传递 歌曲url
	// if (!data) return // true 就是加入歌单一首   false 就是不加入歌单仅播放
	// store.commit('clickSingleSong', list)
}


// 时间格式
function formatTime(time) {
	var minute = Math.floor(time / 60) % 60;
	var second = Math.floor(time) % 60
	return (minute < 10 ? '0' + minute : minute) + ':' +
		(second < 10 ? '0' + second : second)
}
//判断用户是否有权限
function haveToken() {
	const token = uni.getStorageSync('userData');
	if (token == '') {
		uni.showToast({
			title: '请先登录',
			icon: 'error',
			duration: 5000,
		})
		setTimeout(() => {
			uni.reLaunch({
				url: '../../subpag/phoneLogin/phoneLogin'
			})
		}, 1000)
		return false
	}
	return true
}

export default {
	distinct1,
	playMusic,
	pause, //暂停播放
	stop, //停止播放
	formatTime,
	aiginPlay,
	SendMusic,
	lookMusicStatus,
	play,
	sliderPlay,
	haveToken
}
